<?php
/**
* Bysoft
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com and you will be sent a copy immediately.
*
* @category   Bysoft
* @package    Bysoft_Flashnavigator
* @author     Bysoft
* @copyright  Copyright (c) 2009 Bysoft (http://www.bysoft.fr)
* @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*/ 
class Bysoft_Flashnavigator_Adminhtml_FlashnavigatorController extends Mage_Adminhtml_Controller_Action
{

	protected function _initAction() {
		$this->loadLayout()
			->_setActiveMenu('flashnavigator/items')
			->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));

		return $this;
	}

	public function indexAction() {		
		$this->_initAction()
			->renderLayout();
            //$this->_forward('edit');
	}

	public function editAction() {
		$id     = $this->getRequest()->getParam('id');
		
			$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
			if (!empty($data)) {
				//$model->setData($data);
			}

			//Mage::register('flashnavigator_data', $model);

			$this->loadLayout();
			$this->_setActiveMenu('flashnavigator/items');

			$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
			
			$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

			$this->_addContent($this->getLayout()->createBlock('flashnavigator/adminhtml_flashnavigator_edit'))
				->_addLeft($this->getLayout()->createBlock('adminhtml/store_switcher'))
				->_addLeft($this->getLayout()->createBlock('flashnavigator/adminhtml_flashnavigator_edit_tabs'));

			$this->renderLayout();		
	}

	public function newAction() {
		$this->_forward('edit');
	}
	
	/*
	*delete navigator
	*/
	public function deleteAction()
	{
	    $flash_id = $this->getRequest()->getParam('id');
	    $flashnavigator_model = Mage::getModel("flashnavigator/flashnavigator");
	    $flashnavigator_model->load( $flash_id );	    
	    $flashnavigator_model->delete();	    
	    //$flash_dir = Mage::getBaseDir('media')."/slideshow/items/{$flash_id}";
	    $this->_redirect('*/*/index');
	}

	public function saveAction() {
	    $intStoreId = (int) $this->getRequest()->getParam('store');
	    
	    $flashnavigator_model = Mage::getModel("flashnavigator/flashnavigator");
	    $flash_data = array();
	    if( $this->getRequest()->getPost('id') > 0  ){
	        $flash_data['id'] = $this->getRequest()->getPost('id');
	        
	    }	    
	    
	    $flash_data['title'] = $this->getRequest()->getPost('title');
	    $flashnavigator_model->setData( $flash_data );
	    $flashnavigator_model->save();
	    $flash_id = $flashnavigator_model->getData('id');
	    $flash_file_name = "banner_720x180.swf"; //it's better to create var to store this file.  add by Ken.
	    
	    
		if ( $flash_id > 0 && $data = $this->getRequest()->getPost()) {
            
            if( $intStoreId > 0 )
                $filename="slideshow/items/{$flash_id}/{$intStoreId}/settings.xml";
            else 
                $filename="slideshow/items/{$flash_id}/settings.xml";
            
            //create folders.    
            $base_item_dir = dirname( Mage::getBaseDir('media').'/'. $filename );
            $this->make_dir( $base_item_dir );
            /*
            if( !file_exists( $base_item_dir.'/'.$flash_file_name ) ){
                copy( Mage::getBaseDir('media').'/slideshow/items/default/'.$flash_file_name,$base_item_dir.'/'.$flash_file_name );
            }*/
            
            //save id in $data. in some case , id is already existing, but no problem.
            
            foreach( $_FILES as $field_name => $field_value ){
                if(  stristr( $field_name,'filename' ) ){    
        			try {      
        
                        if(isset($data[ $field_name ]['delete'])){
                            $image = stristr( $data[ $field_name ]['value'],'http://' ) ? str_replace( eregi_replace( '\/index\.php\/?','', Mage::getBaseUrl('web') ),'', $data[ $field_name ]['value'] ):$data[ $field_name ]['value'];                                                    if( $intStoreId > 0 && !stristr( $image,"/items/{$flash_id}/{$intStoreId}/" ) || stristr( $image,'/items/default/' ) ){
                                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('flashnavigator')->__('Image:%s can not be deleted.',$image));
                            }else{
                                unlink( Mage::getBaseDir().'/'.$image );
                            }
                        }
        
                        /* Starting upload */
        				$uploader = new Varien_File_Uploader( $field_name );
        
        				// Any extention would work
                   		$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
        				$uploader->setAllowRenameFiles(false);
        
        				// Set the file upload mode
        				// false -> get the file directly in the specified folder
        				// true -> get the file in the product like folders
        				//	(file.jpg will go in something like /media/f/i/file.jpg)
        				$uploader->setFilesDispersion(false);
        
        				// We set media as the upload dir
        				if( $intStoreId > 0 )
        				    $path = Mage::getBaseDir('media') . DS .'slideshow' . DS . 'items' . DS . $flash_id . DS . $intStoreId .DS .'img';
        				else $path = Mage::getBaseDir('media') . DS .'slideshow' . DS . 'items' . DS . $flash_id . DS .'img';
                        $this->make_dir( $path );
        				
        				$uploader->save($path, $_FILES[ $field_name ]['name'] );
        
        
        			} catch (Exception $e) {}
                }
            }//end for loop
    
    		$model = Mage::getModel('flashnavigator/flashnavigator');    
    		try {   			
    
                $this->writeXmlFile($data);    
    			Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('flashnavigator')->__('Item was successfully saved'));
    
    			Mage::getSingleton('adminhtml/session')->setFormData(false);        			
    			$this->_redirect('*/*/edit', array('id' => $flash_id));
    			return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setFormData($data);
                $this->_redirect('*/*/edit', array('id' => $flash_id));
                return;
            }
        }//end if
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('flashnavigator')->__('Unable to find item to save'));
        $this->_redirect('*/*/');
	}



        public function writeXmlFile($data)
        {
        $intStoreId = (int) $this->getRequest()->getParam('store');
        if( $intStoreId > 0 )
            $filename=Mage::getBaseDir()."/media/slideshow/items/{$data['id']}/{$intStoreId}/settings.xml";
        else 
            $filename=Mage::getBaseDir()."/media/slideshow/items/{$data['id']}/settings.xml";
        //print_r($data);

        $content="<?xml version=\"1.0\" encoding=\"UTF-8\"?>

        <!--
        /**
 * Bysoft
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com and you will be sent a copy immediately.
 *
 * @category   Bysoft
 * @package    Bysoft_FlashNavigator
 * @author     Bysoft
 * @author     Samuel Huang
 * @copyright  Copyright (c) 2009 Bysoft (http://www.bysoft.fr)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
 -->

        <banner>
           <links>";

        for($i=0;$i<5;$i++){
            if($data['order'.$i] !=null){
                 $content.="
                         <link>
		        	          <background_image>";
                if($_FILES['filename'.$i]['name'] != null){
                    if( $intStoreId > 0 )
                        $imagename="media/slideshow/items/{$data['id']}/{$intStoreId}/img/".$_FILES['filename'.$i]['name'];
                    else 
                        $imagename="media/slideshow/items/{$data['id']}/img/".$_FILES['filename'.$i]['name'];

                 }
                 elseif(isset($data['filename'.$i]['delete'] )){
                    $imagename='';

                 }
                 elseif(isset($data['filename'.$i]) == false){
                    $imagename='';
                 }
                 else{
                    $imagename=$data['filename'.$i]['value'];
                 }
                 
                 
                if( !empty( $imagename ) && !stristr( $imagename,'http:' ) )
                    $imagename = eregi_replace( '\/index\.php\/?','', Mage::getBaseUrl('web') ) . $imagename;
                
                $content.=$imagename."</background_image>
			                 <link_url>".$data['title'.$i]."</link_url>
                         </link>";
                 }
                 else
                     break;

                }
        $content.="
        </links>
        	<settings>
	        	<DISPLAY_DURATION>".$data['displayduration']."</DISPLAY_DURATION>
               <TRANSITION_DURATION>".$data['transtionduration']."</TRANSITION_DURATION>
               </settings>
        </banner>";

        file_put_contents($filename,$content);

           }

    protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
    {
        $response = $this->getResponse();
        $response->setHeader('HTTP/1.1 200 OK','');
        $response->setHeader('Pragma', 'public', true);
        $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
        $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
        $response->setHeader('Last-Modified', date('r'));
        $response->setHeader('Accept-Ranges', 'bytes');
        $response->setHeader('Content-Length', strlen($content));
        $response->setHeader('Content-type', $contentType);
        $response->setBody($content);
        $response->sendResponse();
        die;
    }
    
    private function make_dir( $dir )
	{
		$dirs = explode("/", $dir);
		
		$str_dir = "";
		for($i=0; $i<count($dirs); $i++)
		{		
			if( $i == 0 )
				$str_dir .= $dirs[$i];
			else $str_dir .= "/{$dirs[$i]}";
			if( !empty( $str_dir ) && !is_dir ($str_dir)) mkdir ($str_dir, 0777);
		}
		
		return ;
	}
}